package com.jacobson.core.widget.keyboard

import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import android.widget.FrameLayout
import com.jacobson.core.R
import com.jacobson.core.utils.AppUtils

/**
 * ================================================
 *
 *  @author Wucz on 2018-08-16 20:44
 * ================================================
 */

class KeyboardChangeListener(
        activity: Activity,
        val immersive: Boolean = true,
        private val onKeyboardChangeListener: ((isShow: Boolean, keyboardHeight: Int) -> Unit)? = null
) : ViewTreeObserver.OnGlobalLayoutListener {
    private var contentView: View? = (activity.findViewById<View>(R.id.content) as FrameLayout).getChildAt(0).apply {
        viewTreeObserver.addOnGlobalLayoutListener(this@KeyboardChangeListener)
    }
    private var usableHeightPrevious = 0
    private var keyboardHeightMaybe = 0
    fun destroy() {
        contentView?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
        contentView = null
    }

    override fun onGlobalLayout() {
        val usableHeightNow = computeUsableHeight()
        if (usableHeightNow != usableHeightPrevious) {
            val usableHeightSansKeyboard = contentView?.rootView?.height ?: 0
            val heightDifference = usableHeightSansKeyboard - usableHeightNow
            if (heightDifference > usableHeightSansKeyboard / 4) {
                // keyboard probably just became visible
                keyboardHeightMaybe = heightDifference
                onKeyboardChangeListener?.invoke(true, heightDifference)
            } else {
                // keyboard probably just became hidden
                onKeyboardChangeListener?.invoke(false, keyboardHeightMaybe)
            }
            usableHeightPrevious = usableHeightNow
        }
    }

    private fun computeUsableHeight(): Int {
        val r = Rect()
        contentView?.getWindowVisibleDisplayFrame(r)
        return r.bottom - r.top + if (immersive) {
            AppUtils.getStatusBarHeight(contentView?.context)
        } else {
            0
        }
    }

}